package com.example.security.controller;

import com.example.security.bean.User;
import com.example.security.dao.UserService;
import com.example.security.event.RegisterEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@RestController
@Slf4j
public class RegisterController {
  private final UserService userService;
  private final ApplicationEventPublisher publisher;

  public RegisterController(UserService userService, ApplicationEventPublisher publisher) {
    this.userService = userService;
    this.publisher = publisher;
  }

  @PostMapping("/register")
  ResponseEntity<?> register(User user) {

    // 注册用户的接口统一加上User的角色
    user.setRoles(Arrays.asList("USER")); // Collections.singletonList("USER"));

    user.setActivated(false);

    if (userService.addUser(user)) {
      // 发布用户注册的事件
      var registerEvent = new RegisterEvent(this, user);

      log.info("publisher thread id: " + String.valueOf(Thread.currentThread().getId()));
      publisher.publishEvent(registerEvent);

      return ResponseEntity.ok("用户注册成功");
    } else {
      return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名或电子邮件已存在");
    }
  }
}
